#!/usr/bin/python
# -*- coding: utf-8 -*-

##
 # Copyright 2009 Caio Souza
 # This file is part of Rpyg.
 #
 # Rpyg is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation, either version 3 of the License, or
 # (at your option) any later version.
 #
 # Rpyg is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
 # along with Rpyg. If not, see <http://www.gnu.org/licenses/>.
 ##

'''Módulo de controle automático dos personagens'''

from rpyg.Controller import Controller
from rpyg.State import *
from rpyg.Utils import *

class Automatic(Controller):
    '''Controla um personagem através de ações predefinidas'''

    def __init__(self, states):
        '''Cria um controle local a partir das ações passadas.'''

        Controller.__init__(self)

        self._moves = []
        self.addStates(states)

    def addStates(self, states):
        '''Adiciona estados a lista de movimentação do personagem.'''
        
        with self._lock:
            for state in states:
                if isinstance(state, State) and hasattr(state, 'key'): self._moves.append(state)
                else:
                    if state in ('n', 'N', KEY_NORTH): state = KEY_NORTH
                    elif state in ('s', 'S', KEY_SOUTH): state = KEY_SOUTH
                    elif state in ('e', 'E', KEY_EAST): state = KEY_EAST
                    elif state in ('w', 'W', KEY_WEST): state = KEY_WEST
        
                    self._moves.append(State(MOVE_KEY, counter = -1, key = state))

    def get(self, i, j):
        '''Retorna a ação que o personagem deverá tomar.'''

        with self._lock:
            if not len(self._moves): return State(DO_NOTHING)
        
            key = None
            move = self._moves[0]
            
            if move.type == MOVE_KEY:
                if self._tilemap.isBlocked(i, j, move.key):
                    if move.counter == 0: del self._moves[0]
                    return State(LOOK_AT, key = move.key)
                
                state = MOVE_KEY
                key = move.key
                
            else: state = move.type
        
            del self._moves[0]
            if move.counter != 0:
                move.counter -= 1
                self._moves.append(move)

            return State(state, key = key)
